package ch.inputRoute;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class LoadFromDbActivity extends ListActivity{
	/** Called when the activity is first created. */
	
	private PathfinderDbAdapter mDbHelper;
	private ListView lv;
	public static final int INSERT_ID = Menu.FIRST;
	public static final int NONE = Menu.NONE;
	public static final int CLEAR_ID = 2;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);

    	  lv = getListView();
    	  lv.setTextFilterEnabled(true);
    	  mDbHelper = new PathfinderDbAdapter(this);
    	  mDbHelper.open();
    	  
    	  fillData();

    	  lv.setOnItemClickListener(new OnItemClickListener() {
    	    public void onItemClick(AdapterView<?> parent, View view,
    	        int position, long id) {
    	      // When clicked, show a toast with the TextView text
    	      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
    	          Toast.LENGTH_SHORT).show();
    	      //ToDo: Map mit Koordinaten laden
    	      Intent myIntent = new Intent(view.getContext(), MapsActivity.class);
				myIntent.putExtra(InputRouteActivity.ROOM_PARAMETER, ((TextView)view).getText().toString());
				startActivityForResult(myIntent, 0);
    	    }
    	  });
    }
    
    private void fillData() {
        // Get all of the positions from the database and create the item list
        Cursor c = mDbHelper.GetAllPlaces();
        startManagingCursor(c);

        String[] from = new String[] { mDbHelper.KEY_DESCRIPTION };
        int[] to = new int[] { R.id.text1 };
        
        SimpleCursorAdapter places =
                new SimpleCursorAdapter(this, R.layout.db_list_item, c, from, to);
            setListAdapter(places);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	boolean result = super.onCreateOptionsMenu(menu);
    	menu.add(NONE, CLEAR_ID, NONE, R.string.ButtonClearDb);
        menu.add(NONE, INSERT_ID, NONE, R.string.ButtonBack);
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
        case INSERT_ID:
        	Intent myIntent = new Intent(this, InputRouteActivity.class);
            startActivityForResult(myIntent, 0);
            return true;
        case CLEAR_ID:
        	mDbHelper.deletePlaces();
        	fillData();
        	return true;
        }
       
        return super.onOptionsItemSelected(item);
    }
    
}
